package br.com.devteam.base.validator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator(value = "DateValidator")
public class DateValidator implements Validator {

	@Override
	public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
			throws ValidatorException {

		if (arg2 != null && !DateValidator.validate(arg2))
			throw new ValidatorException(new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "",
					"Data no formato inválido. dd/mm/aaaa"));
	}

	/**
	 * Aceita da como {@link java.lang.String} ou objeto {@link java.util.Date}
	 * */
	public static boolean validate(Object date) {

		String param = "";
		if (date instanceof Date) {
			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
			param = formatter.format(date);
		} else {
			param = date.toString();
		}

		Pattern p = Pattern
				.compile("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");

		return p.matcher(param).find();
	}
}
